package com.simen.downloader.util;

import android.net.Uri;
import android.text.TextUtils;

import java.io.File;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * Created by zhangming on 16/5/12.
 */
public class Utils {

    public static boolean deleteFile(File file) {
        if (fileExist(file)) {
            boolean result = file.delete();
            if (result) {
                AppLog.d("file " + file.getPath() + " has be deleted");
            } else {
                AppLog.d("delete file " + file.getPath() + " fail");
            }
            return result;
        }
        AppLog.d("file " + file.getPath() + " not exists");
        return true;
    }


    public static boolean fileExist(File file) {
        if (file.exists() && file.isFile()) {
            return true;
        }
        return false;
    }

    public static String getFileNameByUrl(String fileUrl) {
        if (TextUtils.isEmpty(fileUrl)) {
            return null;
        }

        return Uri.parse(fileUrl).getLastPathSegment();
    }

    public static String getExtensionNameByUrl(String fileUrl) {
        if (TextUtils.isEmpty(fileUrl)) {
            return null;
        }

        return getExtensionName(Uri.parse(fileUrl).getLastPathSegment());
    }

    public static String getExtensionName(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length() - 1))) {
                return filename.substring(dot + 1);
            }
        }
        return filename;
    }

    public static String getFileNameNoEx(String filename) {
        if ((filename != null) && (filename.length() > 0)) {
            int dot = filename.lastIndexOf('.');
            if ((dot > -1) && (dot < (filename.length()))) {
                return filename.substring(0, dot);
            }
        }
        return filename;
    }

    public static HttpURLConnection openURLConnection(String url, long writeLength, long total) throws
            IOException {
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setConnectTimeout(Constants.CONNECTTIMEOUT); //设置连接超时
        conn.setReadTimeout(Constants.READTIMEOUT);
        conn.setRequestMethod(Constants.HTTPGET);
        conn.setInstanceFollowRedirects(true);
        if (writeLength != 0) {
            conn.setRequestProperty(Constants.RANGE, "bytes=" + writeLength + "-" + total);
        }
        return conn;
    }

    public static long getReadFileLength(String readfilepath) {
        File file = new File(readfilepath);
        if (!file.exists() || !file.isFile()) {
            return 0;
        }
        return file.length();
    }



}
